<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="类型名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备类型名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['device:deviceType:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Search" @click="toggleSearch">{{
          showSearch ? "隐藏搜索" : "显示搜索"
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="getList"
          >刷新</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="min-height: 500px; height: 600px"
    >
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column
        prop="name"
        align="center"
        label="设备类型名称"
      ></el-table-column>
      <el-table-column
        prop="typeCode"
        align="center"
        label="设备类型编码"
      ></el-table-column>
      <el-table-column prop="energyType" align="center" label="能源类型">
        <template #default="scope">
          <el-tag :type="getEnergyTypeTagType(scope.row.energyType)">
            {{ getEnergyTypeName(scope.row.energyType) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="type" align="center" label="设备类型">
        <template #default="scope">
          {{ getTypeName(scope.row) }}
        </template>
      </el-table-column> -->
      <el-table-column
        align="center"
        prop="createAt"
        label="创建时间"
        sortable
      ></el-table-column>
      <el-table-column label="更新时间" align="center" prop="createAt" sortable>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:deviceType:edit']"
            >修改</el-button
          >
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:deviceType:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改设备类型对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="70%"
      append-to-body
      destroy-on-close
    >
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备类型名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备类型名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="设备类型编码" prop="typeCode">
              <el-input
                v-model="form.typeCode"
                placeholder="请输入设备类型编码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="能源类型" prop="energyType">
              <el-select v-model="form.energyType" placeholder="请选择能源类型">
                <el-option
                  v-for="item in ENERGY_TYPE_OPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="form.id">
          <el-col :span="24">
            <el-form-item label="设备属性">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handlePropertyAdd"
                v-hasPermi="['device:deviceType:propertyAdd']"
                >新增属性</el-button
              >
            </el-form-item>
            <div class="propertyList">
              <el-table
                stripe
                style="height: 400px; width: 100%"
                :data="form.devicePropertyList"
              >
                <el-table-column
                  align="center"
                  prop="name"
                  label="属性名称"
                ></el-table-column>
                <el-table-column
                  align="center"
                  prop="dataCode"
                  label="属性编码"
                ></el-table-column>
                <el-table-column
                  align="center"
                  prop="dataFormCode"
                  label="时序库编码"
                ></el-table-column>
                <el-table-column
                  align="center"
                  prop="groupName"
                  label="属性分组"
                ></el-table-column>
                <el-table-column align="center" prop="kind" label="属性类型">
                  <template #default="scope">
                    {{ scope.row.kind == 0 ? "硬件属性" : "数据属性" }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="dataType"
                  label="属性数据类型"
                >
                  <template #default="scope">
                    {{ getNameByType(scope.row.dataType) }}
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="dataFormContent"
                  label="默认值"
                >
                </el-table-column>
                <el-table-column align="center" prop="dataDw" label="属性单位">
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="dataMultiple"
                  label="系数"
                >
                </el-table-column>
                <el-table-column
                  label="操作"
                  align="center"
                  width="150px"
                  class-name="small-padding fixed-width"
                >
                  <template #default="scope">
                    <el-button
                      link
                      type="text"
                      icon="Edit"
                      @click="handlePropertyUpdate(scope.row)"
                      v-hasPermi="['device:deviceType:propertyEdit']"
                      >修改</el-button
                    >
                    <el-popconfirm
                      title="确定删除此条属性吗?"
                      @confirm="handlePropertyDelete(scope.row)"
                    >
                      <template #reference>
                        <el-button
                          link
                          type="text"
                          icon="Delete"
                          v-hasPermi="['device:deviceType:propertyRemove']"
                          >删除</el-button
                        >
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
            v-hasPermi="['device:deviceType:save']"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :title="propertyDialogParams.title"
      v-model="propertyDialogParams.show"
      style="width: 500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        :model="propertyForm"
        ref="propertyRef"
        :rules="propRules"
        label-width="100px"
      >
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="propertyForm.name" placeholder="请输入属性名称" />
        </el-form-item>
        <el-form-item label="属性编码" prop="dataCode">
          <el-input
            v-model="propertyForm.dataCode"
            placeholder="请输入属性编码"
          />
        </el-form-item>
        <el-form-item label="时序库编码" prop="dataFormCode">
          <el-input
            v-model="propertyForm.dataFormCode"
            placeholder="请输入时序库编码"
          />
        </el-form-item>
        <el-form-item label="属性类型" prop="kind">
          <el-select v-model="propertyForm.kind">
            <el-option
              v-for="item in kindList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="数据类型"
          prop="dataType"
          v-if="propertyForm.kind == 1"
        >
          <el-select v-model="propertyForm.dataType">
            <el-option
              v-for="item in dataTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="数据单位"
          prop="dataDw"
          v-if="propertyForm.kind == 1"
        >
          <el-input
            v-model="propertyForm.dataDw"
            placeholder="请输入属性编码"
          />
        </el-form-item>
        <el-form-item
          label="属性图标"
          prop="dataDw"
          v-if="propertyForm.kind == 1"
        >
          <el-upload
            class="avatar-uploader"
            action="/dev-api/common/oss/upload"
            :show-file-list="false"
            :headers="{
              'X-Noodle-Token': getToken(),
              Authorization: 'Bearer ' + getToken(),
            }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="propertyForm.dataIcon"
              :src="propertyForm.dataIcon"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div style="font-size: 12px; color: #999">
                仅支持 JPG/PNG 格式，大小不超过 500KB。<br />
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="默认值"
          prop="dataFormContent"
          v-if="propertyForm.kind == 0"
        >
          <el-input v-model="propertyForm.dataFormContent"></el-input>
        </el-form-item>
        <el-form-item
          label="属性分组"
          prop="groupId"
          v-if="propertyForm.kind == 1"
        >
          <el-select
            v-model="propertyForm.groupId"
            placeholder="请选择属性分组"
            clearable
          >
            <el-option
              v-for="item in propertyGroupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="系数"
          prop="dataMultiple"
          v-if="propertyForm.kind == 1"
        >
          <el-input
            v-model="propertyForm.dataMultiple"
            type="number"
            placeholder="请输入系数"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitProperty"
            v-hasPermi="['device:deviceType:propertySave']"
            >确 定</el-button
          >
          <el-button @click="propertyDialogParams.show = false"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      style="float: right"
      @current-change="getList"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next"
      :total="pagination.total"
    />
  </div>
</template>

<script setup>
import {
  getDeviceTypeList,
  delDeviceType,
  getDeviceTypeDetailById,
  saveDeviceType,
  delDeviceProperty,
  saveDeviceProperty,
} from "@/api/deviceManage/deviceType";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref, toRefs, getCurrentInstance } from "vue";
import { Plus } from "@element-plus/icons-vue";
import {
  ENERGY_TYPE_OPTIONS,
  getEnergyTypeName,
  getEnergyTypeTagType,
} from "@/utils/enums";
import { getPropertyGroupList } from "@/api/deviceManage/propertyGroup";

const { proxy } = getCurrentInstance();
const tableData = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const kindList = [
  {
    label: "硬件属性",
    value: 0,
  },
  {
    label: "数据属性",
    value: 1,
  },
];
const deviceTypeEnumList = [
  {
    label: "水情",
    value: 100,
  },
  {
    label: "闸门",
    value: 200,
  },
  {
    label: "墒情",
    value: 300,
  },
  {
    label: "水质",
    value: 400,
  },
  {
    label: "气象",
    value: 500,
  },
  {
    label: "流量",
    value: 600,
  },
  {
    label: "泵站",
    value: 700,
  },
  {
    label: "摄像头",
    value: 800,
  },
];
const dataTypeList = [
  {
    label: "字符串",
    value: 0,
  },
  {
    label: "整数型",
    value: 1,
  },
  {
    label: "小数型",
    value: 2,
  },
  {
    label: "布尔型",
    value: 3,
  },
  {
    label: "日期型",
    value: 10,
  },
];
const propertyForm = reactive({
  id: null,
  name: "",
  dataCode: "",
  dataFormCode: "",
  dataType: 0,
  kind: 0,
  dataFormContent: "",
  dataMultiple: 1,
  groupId: null, // 属性分组ID
});
const propertyGroupOptions = ref([]); // 属性分组选项
const propertyDialogParams = reactive({
  show: false,
  title: "新增属性",
});
const data = reactive({
  queryParams: {
    name: "",
  },
  rules: {
    name: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    typeCode: [
      { required: true, message: "设备编码不能为空", trigger: "blur" },
    ],
  },
  propRules: {
    name: [{ required: true, message: "属性名称不能为空", trigger: "blur" }],
    dataCode: [
      { required: true, message: "属性编码不能为空", trigger: "blur" },
    ],
  },
});
const filterTag = (value, row) => {
  return row.kind === value;
};
function getTypeName(row) {
  return deviceTypeEnumList.find((f) => f.value == row.type).label;
}

function getNameByType(type) {
  const typeItem = dataTypeList.find((f) => f.value == type);
  return typeItem ? typeItem.label : "未知类型";
}
const { queryParams, rules, propRules } = toRefs(data);
const form = reactive({});
const handleAvatarSuccess = (res, uploadFile) => {
  ElMessage({
    message: "上传成功！",
    type: "success",
  });
  propertyForm.dataIcon =
    res.data || res.data.fileUrl || res.data.link || res.data.url;
};
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt200k = file.size / 1024 < 500;

  if (!isJpgOrPng) {
    ElMessage.error("上传图片格式应为 JPG 或 PNG!");
  }
  if (!isLt200k) {
    ElMessage.error("上传图片大小不能超过 200KB!");
  }
  return isJpgOrPng && isLt200k;
};
// 获取属性分组列表
function getPropertyGroupOptions() {
  if (!form.energyType) {
    propertyGroupOptions.value = [];
    return;
  }

  getPropertyGroupList({ energyType: form.energyType })
    .then((response) => {
      propertyGroupOptions.value = response.data.list || [];
    })
    .catch((error) => {
      console.error("获取属性分组列表失败:", error);
      propertyGroupOptions.value = [];
    });
}

/** 查询列表 */
function getList() {
  loading.value = true;
  getDeviceTypeList({ ...pagination, ...queryParams.value }).then(
    (response) => {
      tableData.value = response.data.list;
      pagination.total = response.data.totalCount;
      console.log(tableData.value, response);
      loading.value = false;
    }
  );
}
function handlePropertyAdd() {
  propertyDialogParams.show = true;
  propertyDialogParams.title = "新增属性";
  Object.assign(propertyForm, {
    id: null,
    name: "",
    dataCode: "",
    dataFormCode: "",
    dataType: 0,
    kind: 0,
    dataFormContent: "",
    dataDw: "",
    dataIcon: "",
    dataMultiple: 1,
    groupId: null, // 重置属性分组ID
  });

  // 获取属性分组选项
  getPropertyGroupOptions();
}
function submitProperty() {
  proxy.$refs["propertyRef"].validate((valid) => {
    if (valid) {
      // 若未填写时序库编码，默认使用属性编码
      if (!propertyForm.dataFormCode) {
        propertyForm.dataFormCode = propertyForm.dataCode;
      }
      if (propertyForm.kind == 0) {
        propertyForm.dataType = 0; //硬件属性定死为string类型
        saveDeviceProperty(propertyForm).then((res) => {
          ElMessage.success("操作成功！");
          propertyDialogParams.show = false;
          updateDetail();
        });
      } else {
        saveDeviceProperty(propertyForm).then((res) => {
          ElMessage.success("操作成功！");
          propertyDialogParams.show = false;
          updateDetail();
        });
      }
    }
  });
}
function updateDetail() {
  getDeviceTypeDetailById(form.id).then((res) => {
    Object.assign(form, res.data);

    // 如果正在编辑属性，更新属性分组选项
    if (propertyDialogParams.show) {
      getPropertyGroupOptions();
    }
  });
}
function handlePropertyUpdate(row) {
  Object.assign(propertyForm, row);
  propertyDialogParams.show = true;
  propertyDialogParams.title = "编辑属性";

  // 获取属性分组选项
  getPropertyGroupOptions();
}
function handlePropertyDelete(row) {
  if (row.kind == 0) {
    delDeviceProperty([row.id]).then((res) => {
      ElMessage.success("删除成功");
      updateDetail();
    });
  } else {
    delDeviceProperty([row.id]).then((res) => {
      ElMessage.success("删除成功");
      updateDetail();
    });
  }
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  Object.assign(form, {
    id: null,
    kind: 0,
    energyType: 20, // 默认选择电
    //   type: 100,
    name: "",
    typeCode: "",
    //   dataFormType: 1,
    devicePropertyList: [],
  });

  proxy.resetForm("deptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 切换搜索显示/隐藏 */
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  open.value = true;
  title.value = "添加设备类型";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  getDeviceTypeDetailById(row.id).then((res) => {
    Object.assign(form, res.data);
    propertyForm.typeId = res.data.id;
    open.value = true;
    title.value = "修改设备属性";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) {
      if (form.id) {
        saveDeviceType(form).then((response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        saveDeviceType(form).then((response) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  ElMessageBox.confirm(
    '是否确认删除名称为"' + row.name + '"的数据项?',
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      delDeviceType([row.id]).then((res) => {
        getList();
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
}
getList();
</script>
<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";
// 移除固定宽度，使用全局样式
.app-container {
  padding: 10px 20px;
  background: $base-menu-background;
  min-height: 100vh;
}

// 按钮组样式
.mb8 {
  margin-bottom: 10px;
  margin-left: 0 !important;
  margin-right: 0 !important;
  background: #ffffff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &.el-button--primary.is-plain {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }
  }
}

// 对话框样式 - 使用全局样式

// 表单样式已移至全局样式文件 table-global.scss

// 操作按钮样式
:deep(.el-button--text) {
  color: #4fdaca !important;
  font-weight: 600 !important;
  position: relative !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  border-radius: 6px !important;
  padding: 6px 12px !important;

  &:hover {
    color: #32b7cb !important;
    background: linear-gradient(
      135deg,
      rgba(79, 218, 202, 0.1) 0%,
      rgba(50, 183, 203, 0.1) 100%
    ) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 2px 8px rgba(79, 218, 202, 0.2) !important;
  }

  &:active {
    transform: translateY(0) !important;
    box-shadow: 0 1px 4px rgba(79, 218, 202, 0.3) !important;
  }
}

// 更具体的操作按钮样式选择器
::v-deep(.el-button.el-button--text) {
  color: #4fdaca !important;
  font-weight: 600 !important;
  font-size: 13px !important;
  padding: 8px 16px !important;
  margin: 0 6px !important;
  border-radius: 8px !important;
  border: 1px solid transparent !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  position: relative !important;
  overflow: hidden !important;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
    transition: left 0.3s ease;
    z-index: -1;
  }

  &:hover {
    color: #ffffff !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 12px rgba(79, 218, 202, 0.4) !important;
    border-color: #4fdaca !important;
    background: transparent !important;

    &::before {
      left: 0;
    }
  }

  &:active {
    transform: translateY(0) !important;
    box-shadow: 0 2px 6px rgba(79, 218, 202, 0.3) !important;
  }
}

// 确认对话框样式 - 使用全局样式

// 上传组件样式
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #4fdaca;
  }
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

// 分页组件样式 - 使用全局样式
</style>
